package com.withmiku.world.user.service.impl;

import com.withmiku.world.user.entity.PostLike;
import com.withmiku.world.user.repository.PostLikeRepository;
import com.withmiku.world.user.repository.PostRepository;
import com.withmiku.world.user.service.PostLikeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class PostLikeServiceImpl implements PostLikeService {
    private final PostLikeRepository postLikeRepository;
    private final PostRepository postRepository;

    @Autowired
    public PostLikeServiceImpl(PostLikeRepository postLikeRepository,
                               PostRepository postRepository) {
        this.postLikeRepository = postLikeRepository;
        this.postRepository = postRepository;
    }

    @Override
    @Transactional
    public boolean like(Long postId, Long userId) {
        if (isLiked(postId, userId)) {
            return false; // 已点赞
        }

        PostLike like = new PostLike();
        like.setPostId(postId);
        like.setUserId(userId);
        postLikeRepository.save(like);

        // 更新点赞数
        postRepository.incrementLikeCount(postId);
        return true;
    }

    @Override
    @Transactional
    public boolean unlike(Long postId, Long userId) {
        if (!isLiked(postId, userId)) {
            return false; // 还未点赞
        }
        postLikeRepository.deleteByPostIdAndUserId(postId, userId);

        // 更新点赞数
        postRepository.decrementLikeCount(postId);
        return true;
    }

    @Override
    public boolean isLiked(Long postId, Long userId) {
        return postLikeRepository.existsByPostIdAndUserId(postId, userId);
    }

    @Override
    public long countLikes(Long postId) {
        // 直接从Post表中查询而不是用聚合函数计算
        Long count = postRepository.findLikeCountById(postId);

        return count == null ? 0 : count;
    }
}
